package com.sh.caryr.erp.service.impl.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.entity.user.UserRole;
import com.sh.caryr.erp.entity.user.UserRoleAuth;
import com.sh.caryr.erp.mapper.user.UserMapper;
import com.sh.caryr.erp.mapper.user.UserRoleAuthMapper;
import com.sh.caryr.erp.mapper.user.UserRoleMapper;
import com.sh.caryr.erp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author milkeeper
 * @since 2017-11-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserRoleAuthMapper authMapper;

    @Override
    public List<User> findUsersDynamic(Integer current, Integer size, String queryField, String queryValue, Boolean isAccurate, String orderBy) {
        Wrapper wrapper = new EntityWrapper<>();
        if (isAccurate != null) {
            if (isAccurate) {
                wrapper.eq(queryField, queryValue);
            } else {
                wrapper.like(queryField, queryValue);
            }
        }

        return this.findUsersDynamic(new Page<User>(current, size), wrapper.orderBy(orderBy));
    }

    @Override
    public List<User> findUsersDynamic(Integer current, Integer size, Wrapper wrapper, String orderBy) {
        return this.findUsersDynamic(new Page<User>(current, size), wrapper.orderBy(orderBy));
    }

    @Override
    public List<User> findUsersDynamic(Wrapper wrapper) {
        List<User> users = userMapper.selectList(wrapper);
        for (User user : users) {
            getUserDetail(user);
        }
        return users;
    }

    private List<User> findUsersDynamic(Page<User> page, Wrapper<User> wrapper) {
        List<User> users = userMapper.selectPage(page, wrapper);
        for (User user : users) {
            getUserDetail(user);
        }
        return users;
    }
    private void getUserDetail(User user){
        UserRole userRole = userRoleMapper.selectById(user.getUserRoleId());
        if(userRole!=null){
            Wrapper<UserRoleAuth> entityWrapper = new EntityWrapper<UserRoleAuth>().eq("roleId", userRole.getId());
            userRole.setAuthList(authMapper.selectList(entityWrapper));
            user.setUserRole(userRole);
        }
    }
}
